﻿#include "controlwidget.h"
#include <QMessageBox>
#include<Windows.h>
#include<QElapsedTimer>
#include<QCoreApplication>
#include"ctradebymarketdata.h"
#include"ufxconfig.h"

extern CTradeByMarketData* g_pCTradeByMarketData;

ControlWidget::ControlWidget(QWidget *parent) :
    QWidget(parent)
{
    setMaximumSize(270, 400);
    //批量下单的单号
    m_BatchNO       = 1000;
    m_dHighestPrice = 0;
    m_dLowestPrice  = 0;
    m_futu_exch_type = "";
    m_vContracts.clear();
    m_bAutoFlg      = false;

    setupViews();
}


void ControlWidget::SlotSetHandsTimes(int times){
	this->m_HandsTimesSpinBox->setValue(times);
}
QString ControlWidget::GetContractCode(){
	return m_ContractLineEdit->text();
}

int  ControlWidget::GetTotalHands(){
	return m_OrderCntSpinBox->text().toInt() * m_HandsTimesSpinBox->text().toInt();
}

QString ControlWidget::GetFutuExchType(){
	return m_futu_exch_type;
}
void ControlWidget::SetEnableAmount(int iAmount){
    LabelCnt->setText(QString::number(iAmount));
}

void ControlWidget::SetOrderInfo(char bs,char c_direction,char c_hedge,double en_entrust_price,int FocusType){
    ///买卖方向
    if(bs == '1'){
        m_BSRadioButton1->setChecked(true);
    }else if(bs == '2'){
        m_BSRadioButton2->setChecked(true);
    }
    ///开平仓
    if(c_direction == '1'){
        m_OCRadioButton1->setChecked(true);
    }else if(c_direction == '2'){
        m_OCRadioButton2->setChecked(true);
    }else if(c_direction == '4'){
        m_OCRadioButton3->setChecked(true);
    }
    ///组合投机套保标志 '0'	投机     '1'	套保
    c_hedge = '0';

    m_SpecifiedPriceSpinBox->setValue(en_entrust_price);

    switch(FocusType){
    case 2://填单后光标不动
        break;
    case 3://填单后光标到合约代码
        m_ContractLineEdit->setFocus();
        break;
    case 4://填单后光标到买卖
        m_BSRadioButton1->setFocus();
        break;
    case 5://填单后光标到开平
        m_OCRadioButton1->setFocus();
        break;
    case 6://填单后光标到数量
        m_OrderCntSpinBox->setFocus();
        break;
    case 7://填单后光标到价格
        m_SpecifiedPriceSpinBox->setFocus();
        break;
    case 8://填单后光标到下单按钮
        break;
    default:
        break;
    }
}

void ControlWidget::setupViews()
{
    LabelCnt = new QLabel(QStringLiteral("可开手数"));
    LabelBuy1 = new QLabel(QStringLiteral("买一价"));
    LabelSell1 = new QLabel(QStringLiteral("卖一价"));
    LabelBuy1Cnt = new QLabel(QStringLiteral("买一量"));
    LabelSell1Cnt = new QLabel(QStringLiteral("卖一量"));
    LabelTop = new QLabel(QStringLiteral("涨停"));
    LabelBottom = new QLabel(QStringLiteral("跌停"));


    MainLayout = new QGridLayout(this);
    DropLayout = new QHBoxLayout;
    QuickLayout = new QHBoxLayout;

    QLabel* AccountLabel = new QLabel(QStringLiteral("资金账号:"));
    m_AccountCombox = new QComboBox;
    m_AccountCheckbox = new QCheckBox;
    QLabel* AccountDropDown = new QLabel(QStringLiteral("显示下拉"));

    QLabel* OrderTypeLabel = new QLabel(QStringLiteral("订单类型:"));
    m_OrderTypeCombox = new QComboBox;
    m_OrderTypeCheckbox = new QCheckBox;
    QLabel* OrderTypeDropDown = new QLabel(QStringLiteral("快速下单"));
	m_OrderTypeCombox->addItem(QStringLiteral("限价"));
	m_OrderTypeCombox->addItem(QStringLiteral("市价"));
    m_OrderTypeCombox->addItem(QStringLiteral("套保"));
    m_OrderTypeCombox->addItem(QStringLiteral("套利"));

    QLabel* ContractLabel = new QLabel(QStringLiteral("合约代码:"));
    m_ContractLineEdit = new QLineEdit("");

    QLabel* BSLabel = new QLabel(QStringLiteral("买卖:"));
    m_BSRadioButton1 = new QRadioButton(QStringLiteral("买入"));
    m_BSRadioButton2 = new QRadioButton(QStringLiteral("卖出"));
    m_BSRadioButton1->setChecked(true);

    QLabel* OCLabel = new QLabel(QStringLiteral("开平:"));
    m_OCRadioButton1 = new QRadioButton(QStringLiteral("开仓"));
    m_OCRadioButton2 = new QRadioButton(QStringLiteral("平仓"));
    m_OCRadioButton3 = new QRadioButton(QStringLiteral("平今"));
    m_OCRadioButton1->setChecked(true);

    //m_SpecifiedPriceButton = new QPushButton(QStringLiteral("指定价"));
    QLabel* PriceLabel = new QLabel(QStringLiteral("价格:"));
    m_SpecifiedPriceSpinBox = new QDoubleSpinBox;                       //创建SpinBox
    m_SpecifiedPriceSpinBox->setRange(0, 100000);                           //设置spinBox的值范围

    QLabel* OrderCntLabel = new QLabel(QStringLiteral("下单手数"));
    m_OrderCntSpinBox = new QSpinBox;                       //创建SpinBox

	QLabel* HandsTimes = new QLabel(QStringLiteral("下单倍数"));
	m_HandsTimesSpinBox = new QSpinBox;


    m_OrderButton = new QPushButton(QStringLiteral("委托"));
    m_OrderButton->setFixedHeight(60);
    m_ConditionButton = new QPushButton(QStringLiteral("Auto"));
    m_ConditionButton->setFixedHeight(35);
    m_PreentrustButton = new QPushButton(QStringLiteral("Stop"));
    m_PreentrustButton->setFixedHeight(35);

    DropLayout->addWidget(m_AccountCheckbox);
    DropLayout->addWidget(AccountDropDown);
    DropLayout->addStretch();

    MainLayout->addWidget(AccountLabel,0,0,1,1);
    MainLayout->addWidget(m_AccountCombox,0,1,1,2);

    QuickLayout->addWidget(m_OrderTypeCheckbox);
    QuickLayout->addWidget(OrderTypeDropDown);
    QuickLayout->addStretch();

    MainLayout->addWidget(OrderTypeLabel,1,0,1,1);
    MainLayout->addWidget(m_OrderTypeCombox,1,1,1,2);
    //MainLayout->addLayout(QuickLayout,1,3,1,2);

    MainLayout->addWidget(ContractLabel,2,0,1,1);
    MainLayout->addWidget(m_ContractLineEdit,2,1,1,2);

    QHBoxLayout *BSLaybox = new QHBoxLayout;
    BSLaybox->addWidget(BSLabel,Qt::AlignLeft);
    BSLaybox->addWidget(m_BSRadioButton1,Qt::AlignLeft);
    BSLaybox->addWidget(m_BSRadioButton2,Qt::AlignLeft);
    BSLaybox->addStretch(1);
    MainLayout->addLayout(BSLaybox,3,0,1,4);

    QHBoxLayout *OCLaybox = new QHBoxLayout;
    OCLaybox->addWidget(OCLabel);
    OCLaybox->addWidget(m_OCRadioButton1);
    OCLaybox->addWidget(m_OCRadioButton2);
    OCLaybox->addWidget(m_OCRadioButton3);
    MainLayout->addLayout(OCLaybox,4,0,1,4);

    MainLayout->addWidget(OrderCntLabel,6,0,1,1);//手数
    MainLayout->addWidget(m_OrderCntSpinBox,6,1,2,2);
    m_OrderCntSpinBox->setFixedHeight(25);

    MainLayout->addWidget(HandsTimes,8,0,1,1);//倍数
    MainLayout->addWidget(m_HandsTimesSpinBox,8,1,2,2);
    m_HandsTimesSpinBox->setFixedHeight(25);

    MainLayout->addWidget(PriceLabel,10,0,1,1);//价格
    MainLayout->addWidget(m_SpecifiedPriceSpinBox,10,1,2,2);
    m_SpecifiedPriceSpinBox->setFixedHeight(25);

    MainLayout->addWidget(LabelCnt,6,3,1,1);
    MainLayout->addWidget(LabelTop,8,3,1,1);

    QLabel* tmp1 =  new QLabel(QStringLiteral("/"));
    QLabel* tmp2 =  new QLabel(QStringLiteral("/"));
    MainLayout->addWidget(LabelBuy1,9,3,1,1);
    MainLayout->addWidget(tmp1,9,4,1,1);
    MainLayout->addWidget(LabelBuy1Cnt,9,5,1,1);

    MainLayout->addWidget(LabelSell1,10,3,1,1);
    MainLayout->addWidget(tmp2,10,4,1,1);
    MainLayout->addWidget(LabelSell1Cnt,10,5,1,1);

    MainLayout->addWidget(LabelBottom,11,3,1,1);

    MainLayout->addWidget(m_OrderButton,12,0,1,3);
    //MainLayout->addWidget(m_ConditionButton,10,2,0,1);
    //MainLayout->addWidget(m_PreentrustButton,10,2,2,1);
    //m_PreentrustButton->setEnabled(false);

    MainLayout->setSpacing(4);
    MainLayout->setMargin(4);

    m_conditionDialog = new conditionDialog;

    //点击委托按钮事件响应
    connect(m_OrderButton,SIGNAL(clicked()),this,SLOT(OnEntrust()));

    //绑定用户切换订单类型 更改价格的事件响应
    connect(m_OrderTypeCombox,SIGNAL(currentTextChanged(QString)),this,SLOT(OrderTypeChanged(QString)));

    connect(m_BSRadioButton1,SIGNAL(clicked()),this,SLOT(SlotBuyRadioBtnClicked()));
    connect(m_BSRadioButton2,SIGNAL(clicked()),this,SLOT(SlotSellRadioBtnClicked()));
    connect(m_SpecifiedPriceSpinBox,SIGNAL(valueChanged(double)),this,SLOT(SlotValueChanged(double)));

    LabelBuy1->installEventFilter(this);
    LabelSell1->installEventFilter(this);
    LabelTop->installEventFilter(this);
    LabelBottom->installEventFilter(this);
}

bool ControlWidget::eventFilter(QObject *obj, QEvent *ev){
    if (obj == LabelBuy1 || obj == LabelSell1 || obj == LabelBottom || obj == LabelTop) {
        if (ev->type() == QEvent::MouseButtonPress) {
            QString price = ((QLabel*)obj)->text();//获取点击Label的文本
            m_SpecifiedPriceSpinBox->setValue(price.toDouble());
            return true;
        } else {
            return false;
        }
    }else{
        // pass the event on to the parent class
        return QWidget::eventFilter(obj, ev);
    }
}

void ControlWidget::SlotValueChanged(double price){
    QString ordertype = m_OrderTypeCombox->currentText();
    QString futucode  = m_ContractLineEdit->text();
    ///买卖方向
    if(m_BSRadioButton1->isChecked()){
        emit SigGetOpenRatio('1',ordertype,futucode,price);///买入
    }else if(m_BSRadioButton2->isChecked()){
        emit SigGetOpenRatio('2',ordertype,futucode,price);///卖出
    }
}

void ControlWidget::SlotBuyRadioBtnClicked(){
    ///买卖方向
    if(m_BSRadioButton1->isChecked()){
        //this->m_SpecifiedPriceSpinBox->setValue(m_dLowestPrice);///买入
    }else if(m_BSRadioButton2->isChecked()){
        //this->m_SpecifiedPriceSpinBox->setValue(m_dHighestPrice);///卖出
    }
}
void ControlWidget::SlotSellRadioBtnClicked(){
    ///买卖方向
    if(m_BSRadioButton1->isChecked()){
        //this->m_SpecifiedPriceSpinBox->setValue(m_dLowestPrice);///买入
    }else if(m_BSRadioButton2->isChecked()){
        //this->m_SpecifiedPriceSpinBox->setValue(m_dHighestPrice);///卖出
    }
}

void ControlWidget::OrderTypeChanged(QString OrderType){
    if(OrderType == QStringLiteral("市价")){
        m_SpecifiedPriceSpinBox->setValue(0.0);
        m_SpecifiedPriceSpinBox->setEnabled(false);
    }else{
        m_SpecifiedPriceSpinBox->setEnabled(true);
    }
}

/**
 * 委托按钮触发事件响应
 * @brief ControlWidget::OnEntrust
 */
void ControlWidget::OnEntrust(){

    int iOrderCnt = m_OrderCntSpinBox->text().toInt();
    if( 0 == iOrderCnt ){
        QMessageBox::critical(NULL,QString("ERROR"),QStringLiteral("请输入有效的总下单数！"));
        return;
    }else{
        //批量单请求
        int iCnt = m_OrderCntSpinBox->text().toInt();///数量
		int iTimes = m_HandsTimesSpinBox->text().toInt();

        QString contractName;
        char    bs;
        char c_direction;
        char c_hedge;
        int l_entrust_amount;
        double en_entrust_price;

        ///合约代码
        if(m_ContractLineEdit->text() == ""){
            QMessageBox::critical(NULL,QString("ERROR"),QStringLiteral("请输入有效的合约代码！"));
            return;
        }else{
            contractName = m_ContractLineEdit->text();
        }
        ///买卖方向    '2'	卖出
        if(m_BSRadioButton1->isChecked()){
            bs = '1';//'1'	买入
        }else if(m_BSRadioButton2->isChecked()){
            bs = '2';//'2'	卖出
        }

        if(m_OCRadioButton1->isChecked()){//开仓
            c_direction='1';
        }else if(m_OCRadioButton2->isChecked()){//平仓
            c_direction='2';
        }else if(m_OCRadioButton3->isChecked()){//平今仓
            c_direction='4';
        }
        ///组合投机套保标志 '0'	投机     '1'	套保
        c_hedge = '0';
        en_entrust_price = m_SpecifiedPriceSpinBox->text().toDouble();

        if(0 != iCnt ){
            l_entrust_amount = iCnt*iTimes;
        }else{
            QMessageBox::critical(NULL,QString("ERROR"),QStringLiteral("请输入有效的每单手数！"));
        }

        //报单操作
         emit SigOrderInsert(m_futu_exch_type.toStdString().c_str(),contractName.toStdString().c_str(),bs,c_direction,c_hedge,l_entrust_amount,en_entrust_price);
    }
}

//点击预埋按钮事件响应
void ControlWidget::OnPreEntrust(){
    m_bAutoFlg = false;
}
void ControlWidget::SlotUpdateShowInfo(double buy1, double buy1cnt,double sell1,double sell1cnt){
    ///买一价
    LabelBuy1->setText(QString::number(buy1));
    ///买一量
    LabelBuy1Cnt->setText(QString::number(buy1cnt));
    ///卖一价
    LabelSell1->setText(QString::number(sell1));
    ///卖一量
    LabelSell1Cnt->setText(QString::number(sell1cnt));
}
void ControlWidget::SelectContract(const QModelIndex & index){

    clsContract oContractTmp;

	int iRow = index.row();
	//合约
	QModelIndex oContract = index.sibling(iRow,0);
	QString strContract = oContract.data().toString();
    oContractTmp.strContract = strContract;
	this->m_ContractLineEdit->setText(strContract);
    ///买一价
    QModelIndex oBuy1Price = index.sibling(iRow,2);
    LabelBuy1->setText(QString::number(oBuy1Price.data().toDouble()));
    ///买一量
    QModelIndex oBuy1Cnt = index.sibling(iRow,3);
    LabelBuy1Cnt->setText(QString::number(oBuy1Cnt.data().toDouble()));
    ///卖一价
    QModelIndex oSell1Price = index.sibling(iRow,4);
    LabelSell1->setText(QString::number(oSell1Price.data().toDouble()));
    ///卖一量
    QModelIndex oSell1Cnt = index.sibling(iRow,5);
    LabelSell1Cnt->setText(QString::number(oSell1Cnt.data().toDouble()));
    ///涨停板价格
    QModelIndex oHighestPrice = index.sibling(iRow,14);
    m_dHighestPrice = oHighestPrice.data().toDouble();
    oContractTmp.dHighestPrice = m_dHighestPrice;
    LabelTop->setText(QString::number(m_dHighestPrice));
    ///跌停板价格
    QModelIndex oLowestPrice = index.sibling(iRow,15);
    m_dLowestPrice = oLowestPrice.data().toDouble();
    oContractTmp.dLowestPrice = m_dLowestPrice;
    LabelBottom->setText(QString::number(m_dLowestPrice));

    QModelIndex ofutuexchtype = index.sibling(iRow,7);
    m_futu_exch_type = ofutuexchtype.data().toString();
    oContractTmp.strfutuExchType = m_futu_exch_type;

    int iCnt = m_vContracts.size();
    int iFlg = true;
    for( int i =0; i < iCnt; i ++){
        if(m_vContracts[i].strContract == strContract){
            iFlg = false;
        }
    }
    if(iFlg){
        m_vContracts.push_back(oContractTmp);
    }

    ///最新价
    QModelIndex oLastPrice = index.sibling(iRow,1);
    this->m_SpecifiedPriceSpinBox->setValue(oLastPrice.data().toDouble());

    ///手数
    /// //从配置文件中获取默认下单手数
    QString cnt = UFXConfig::getInstance()->GetString("Default","Count","1");
    this->m_OrderCntSpinBox->setValue(cnt.toInt());
	this->m_HandsTimesSpinBox->setValue(1);
}
